//
//  CompanyVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/3/6.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "CompanyVC.h"
#import "HXTagsView.h"
#import "HXTagAttribute.h"
#import "InterviewExperienceTableViewCell.h"
#import "CompanyJobTableViewCell.h"
#import "CompanyReviewCell.h"
#import "CompanyCommentModel.h"
#import "JobModel.h"
#import "UITableView+Empty.h"

@interface CompanyVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *arrData;

@property (weak, nonatomic) IBOutlet UIButton *typeButton1;
@property (weak, nonatomic) IBOutlet UIView *typeLine1;
@property (weak, nonatomic) IBOutlet UIButton *typeButton2;
@property (weak, nonatomic) IBOutlet UIView *typeLine2;
@property (weak, nonatomic) IBOutlet UIButton *typeButton3;
@property (weak, nonatomic) IBOutlet UIView *typeLine3;


@property (weak, nonatomic) IBOutlet UILabel *companyDetailLable;

@property (weak, nonatomic) IBOutlet HXTagsView *tagBackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightOfTags;

@property (weak, nonatomic) IBOutlet UILabel *addressLabel;


@property (strong, nonatomic) IBOutlet UIView *topView;

@property (assign, nonatomic) NSInteger selectedType;
@property (weak, nonatomic) IBOutlet UIView *jobTypeBackView;
@property (weak, nonatomic) IBOutlet HXTagsView *jobTypeView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *jobTypeHeight;

@property (nonatomic, strong) HXTagCollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSMutableArray *commentArray;
@property (nonatomic, strong) NSMutableArray *positionArray;
@property (nonatomic, strong) UIButton *selectedBtn;
@property (nonatomic, strong) NSMutableArray *jobTypeArray;

@end

@implementation CompanyVC {
    NSInteger _positionPageNo;
    NSInteger _commentPageNo;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11.0) {
        self.navViewTopHeight.constant = 0;
    } else {
        self.navViewTopHeight.constant = 20;
    }
    
    [self setupSubViews];
    
    _positionPageNo = 1;
    
    [self loadCompanyData];
    [self getPositionListCountByCompanyId];
    [self.tableView.mj_header beginRefreshing];
}

- (void)setupSubViews {
    self.selectedType = 1;
//    self.arrData = @[@"",@"",@"",@"",@""];
    [self loadHeaderHeight];
    self.tableView.tableHeaderView = self.topView;
    [self.tableView registerNib:[UINib nibWithNibName:@"CompanyJobTableViewCell" bundle:nil] forCellReuseIdentifier:@"CompanyJobTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CompanyReviewCell class]) bundle:nil] forCellReuseIdentifier:@"CompanyReviewCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.estimatedRowHeight = 184.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _commentPageNo = 1;
        [self getCommentListByCompanyId];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _commentPageNo += 1;
        [self getCommentListByCompanyId];
    }];
    
    [self setupCompanyTagsView];
    [self setupCompanyPositionTagsView];
}

- (void)setupCompanyTagsView {
    _tagBackView.completion = ^(NSArray *selectTags,NSInteger currentIndex) {
        NSLog(@"selectTags:%@ currentIndex:%ld",selectTags, (long)currentIndex);
    };
    _tagBackView.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    HXTagAttribute *model = [[HXTagAttribute alloc]init];
    model.borderWidth  = 0;
    model.borderColor  = kClearColor;
    model.cornerRadius  = 8;
    model.titleSize = 11;
    model.textColor = UIColorFromRGB(0x00BCCC);
    model.selectedTextColor = UIColorFromRGB(0x00BCCC);
    model.normalBackgroundColor  = UIColorFromRGB(0xE7F4F6);
    model.selectedBackgroundColor  = UIColorFromRGB(0xE7F4F6);
    model.tagSpace  = 15;
    
    _tagBackView.tagAttribute = model;
    
    HXTagCollectionViewFlowLayout *flowLayout = [[HXTagCollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    flowLayout.itemSize = CGSizeMake(79,20);
    flowLayout.sectionInset = UIEdgeInsetsMake(0.0f, 0.0f, 10.0f, 10.0f);
    self.flowLayout = flowLayout;
    _tagBackView.layout = flowLayout;
    
    [_tagBackView reloadData];
    
//    _tagBackView.tags = @[@"员工旅游",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处"];
//
//    [_tagBackView reloadData];
    CGFloat height = [HXTagsView getHeightWithTags:self.tagBackView.tags layout:flowLayout tagAttribute:self.tagBackView.tagAttribute width:kScreenWidth-30];
    self.heightOfTags.constant = height;
}

- (void)setupCompanyInfoData {
    [self.headerCompanyIconIV sd_setImageWithURL:ImageURLWithKey(self.companyModel.companyLogo) placeholderImage:PlaceholderImageCompany];
    self.headerCompanyNameL.text = self.companyModel.companyName;
    self.headerCompanyInfoL.text = [NSString stringWithFormat:@"%@/%@/%@", self.companyModel.industryName, self.companyModel.financingScaleName, self.companyModel.personnelScaleName];
    self.headerCompanyRegionL.text = self.companyModel.regionName;
    self.companyDetailLable.text = self.companyModel.companyIntroduction;
    self.addressLabel.text = (self.companyModel.companyAddress && self.companyModel.companyAddress.length > 0) ? self.companyModel.companyAddress : self.companyModel.regionName;
    // 公司标签
    NSArray *tags = [self.companyModel.tags componentsSeparatedByString:@","];
    _tagBackView.tags = tags;
    [_tagBackView reloadData];
}

-(void)setupCompanyPositionTagsView {
    _jobTypeView.completion = ^(NSArray *selectTags,NSInteger currentIndex) {
        NSLog(@"selectTags:%@ currentIndex:%ld",selectTags, (long)currentIndex);
    };
    _jobTypeView.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    HXTagAttribute *model = [[HXTagAttribute alloc]init];
    model.borderWidth  = 0;
    model.borderColor  = kClearColor;
    model.cornerRadius  = 3;
    model.titleSize  = 12;
    model.textColor  = UIColorFromRGB(0x59696D);
    model.selectedTextColor  = [UIColor whiteColor];
    model.normalBackgroundColor  = UIColorFromRGB(0xffffff);
    model.selectedBackgroundColor  = UIColorFromRGB(0x42CDD9);
    model.tagSpace  = 15;
    model.keyColor = kRedColor;
    _jobTypeView.tagAttribute = model;
    
    HXTagCollectionViewFlowLayout *flowLayout = [[HXTagCollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    flowLayout.itemSize = CGSizeMake(79,32);
    flowLayout.sectionInset = UIEdgeInsetsMake(0.0f, 0.0f, 10.0f, 10.0f);
    _jobTypeView.layout = flowLayout;
    
    [_jobTypeView reloadData];
    
//    _jobTypeView.tags = @[@"推荐",@"技术",@"产品",@"设计",@"供应链",@"运营",@"酒店管理",@"java中高级开发工程师"];
    _jobTypeView.tags = @[];
    [_jobTypeView reloadData];
    CGFloat height = [HXTagsView getHeightWithTags:self.jobTypeView.tags layout:flowLayout tagAttribute:self.jobTypeView.tagAttribute width:kScreenWidth-30];
    self.jobTypeHeight.constant = height;
}

-(void)loadHeaderHeight{
    self.topView.clipsToBounds = YES;
    if (self.selectedType == 1) {
        CGFloat height = 238;
        self.topView.frame = CGRectMake(0, 0, kScreenWidth, height);
    } else if (self.selectedType == 3) {
        CGFloat height = 228 + self.jobTypeHeight.constant + 15;
        self.topView.frame = CGRectMake(0, 0, kScreenWidth, height);
    } else{
        [self.companyDetailLable sizeToFit];
        [self.addressLabel sizeToFit];
        CGFloat height = 482.5 + self.heightOfTags.constant + self.companyDetailLable.mj_h + self.addressLabel.mj_h-18.5;
        self.topView.frame = CGRectMake(0, 0, kScreenWidth, height);
    }
    self.tableView.tableHeaderView = self.topView;
    [self.tableView reloadData];
}

- (IBAction)typeButtonClick:(UIButton *)sender {
    if (self.selectedBtn == sender) {
        return;
    }
    
    if (self.typeButton1 == sender) {
        
        self.typeButton2.selected = NO;
        self.typeButton3.selected = NO;
        self.typeButton1.selected = YES;
        
        self.typeLine1.hidden = NO;
        self.typeLine2.hidden = YES;
        self.typeLine3.hidden = YES;
        
        self.jobTypeBackView.hidden = YES;
        self.selectedType = 1;
        self.selectedBtn = sender;
//        self.arrData = @[@"",@"",@"",@"",@""];
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _commentPageNo = 1;
            [self getCommentListByCompanyId];
        }];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _commentPageNo += 1;
            [self getCommentListByCompanyId];
        }];
        
        if (self.commentArray.count == 0) {
            [self.tableView.mj_header beginRefreshing];
        }
        
        [self loadHeaderHeight];
        
    } else if (sender == self.typeButton2) {
        self.typeButton2.selected = YES;
        self.typeButton3.selected = NO;
        self.typeButton1.selected = NO;
        
        self.typeLine1.hidden = YES;
        self.typeLine2.hidden = NO;
        self.typeLine3.hidden = YES;
        
        self.jobTypeBackView.hidden = YES;
        self.selectedType = 2;
//        self.arrData = @[];
        self.selectedBtn = sender;
        self.tableView.mj_header = nil;
        self.tableView.mj_footer = nil;
        
        [self.tableView reloadData];
        [self loadHeaderHeight];
    } else{
        self.typeButton2.selected = NO;
        self.typeButton3.selected = YES;
        self.typeButton1.selected = NO;
        
        self.typeLine1.hidden = YES;
        self.typeLine2.hidden = YES;
        self.typeLine3.hidden = NO;
        
//        self.arrData = @[@"",@"",@"",@"",@""];
        self.selectedType = 3;
        self.jobTypeBackView.hidden = NO;
        self.selectedBtn = sender;
        
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _positionPageNo = 1;
            [self getCompanyPositionJobType];
            [self getPositionListByCompanyId];
        }];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _positionPageNo += 1;
            [self getPositionListByCompanyId];
        }];
        
        if (self.positionArray.count == 0) {
            [self.tableView.mj_header beginRefreshing];
        }
        [self loadHeaderHeight];
    }
}


#pragma mark - 根据企业ID查询企业信息
- (void)loadCompanyData {
    WS(weakSelf)
    
    [SendRequest getCompanyInfoByCompanyId:self.companyId result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"根据企业ID查询企业信息 = %@", [result objectForKey:@"data"]);
            weakSelf.companyModel = [CompanyModel mj_objectWithKeyValues:[result objectForKey:@"data"]];
            [weakSelf setupCompanyInfoData];
            
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

#pragma mark - 查询企业职位列表
/** 查询企业职位列表 */
- (void)getPositionListByCompanyId {
    WS(weakSelf)
    
    [SendRequest getPostionListByCompanyId:self.companyModel.companyId andPageNo:[NSString stringWithFormat:@"%zd", _positionPageNo] andJobId:@"" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询企业职位列表 = %@", [[result objectForKey:@"data"] objectForKey:@"list"]);
            NSInteger totalCount = [[[result objectForKey:@"data"] objectForKey:@"totalCount"] integerValue];
//            [weakSelf.typeButton3 setTitle:[NSString stringWithFormat:@"在招职位(%zd)", totalCount] forState:UIControlStateNormal];
            if (totalCount > 0) {
                [weakSelf.typeButton3 setTitle:[NSString stringWithFormat:@"在招职位(%zd)", totalCount] forState:UIControlStateNormal];
            } else {
                [weakSelf.typeButton3 setTitle:@"在招职位" forState:UIControlStateNormal];
            }
            
            NSArray *datas = [PositionModel mj_objectArrayWithKeyValuesArray:[[result objectForKey:@"data"] objectForKey:@"list"]];
            
            if (_positionPageNo == 1) {
                [weakSelf.positionArray removeAllObjects];
                [weakSelf.positionArray addObjectsFromArray:datas];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
            } else {
                [weakSelf.positionArray addObjectsFromArray:datas];
                [weakSelf.tableView reloadData];
                if (datas.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

/** 查询企业职位列表 */
- (void)getPositionListCountByCompanyId {
    WS(weakSelf)
    
    [SendRequest getPostionListByCompanyId:self.companyModel.companyId andPageNo:[NSString stringWithFormat:@"%zd", _positionPageNo] andJobId:@"" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询企业职位列表 = %@", [[result objectForKey:@"data"] objectForKey:@"list"]);
            NSInteger totalCount = [[[result objectForKey:@"data"] objectForKey:@"totalCount"] integerValue];
            if (totalCount > 0) {
                [weakSelf.typeButton3 setTitle:[NSString stringWithFormat:@"在招职位(%zd)", totalCount] forState:UIControlStateNormal];
            } else {
                [weakSelf.typeButton3 setTitle:@"在招职位" forState:UIControlStateNormal];
            }
            
        }
    }];
}

#pragma mark - 查询公司点评
/** 查询公司点评 */
- (void)getCommentListByCompanyId {
    WS(weakSelf)
    [SendRequest getCompanyIncumbentCommentsByCompanyId:self.companyId andPageNo:[NSString stringWithFormat:@"%zd", _commentPageNo] result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询公司点评列表 = %@", [[result objectForKey:@"data"] objectForKey:@"list"]);
            
            NSArray *datas = [CompanyCommentModel mj_objectArrayWithKeyValuesArray:[[result objectForKey:@"data"] objectForKey:@"list"]];
            
            if (_commentPageNo == 1) {
                [weakSelf.commentArray removeAllObjects];
                [weakSelf.commentArray addObjectsFromArray:datas];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
            } else {
                [weakSelf.commentArray addObjectsFromArray:datas];
                [weakSelf.tableView reloadData];
                if (datas.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

#pragma mark - 查询企业职位列表上面的标签
- (void)getCompanyPositionJobType {
    WS(weakSelf)
    [SendRequest getCompanyPositionJobTypeCompanyId:self.companyModel.companyId result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询企业职位列表上面的标签 = %@", [result objectForKey:@"data"]);
            
            NSArray *datas = [JobModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"data"]];
            
            [weakSelf.jobTypeArray removeAllObjects];
            [weakSelf.jobTypeArray addObjectsFromArray:datas];
            
            [weakSelf resetJobTypeListView];
            [weakSelf loadHeaderHeight];
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

- (void)resetJobTypeListView {
    NSMutableArray *tags = [[NSMutableArray alloc] init];
    for (JobModel *job in self.jobTypeArray) {
        [tags addObject:job.jobName];
    }
    _jobTypeView.tags = tags;
    [_jobTypeView reloadData];
    CGFloat height = [HXTagsView getHeightWithTags:self.jobTypeView.tags layout:self.flowLayout tagAttribute:self.jobTypeView.tagAttribute width:kScreenWidth-30];
    self.jobTypeHeight.constant = height + 15;
}

#pragma mark ------tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.selectedType == 1) {
        return self.commentArray.count;
    } else if (self.selectedType == 3) {
        return self.positionArray.count;
    } else {
        return 0;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 65;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectedType == 1) {
        CompanyReviewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CompanyReviewCell"];
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        cell.model = [self.commentArray objectAtIndex:indexPath.row];
        return cell;
    } else {
        static NSString *identifier = @"CompanyJobTableViewCell";
        CompanyJobTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        cell.model = [self.positionArray objectAtIndex:indexPath.row];
        return cell;
    }
}


- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
}

- (IBAction)companyDetailMoreClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.companyDetailLable.numberOfLines = 0;
    }else{
        self.companyDetailLable.numberOfLines = 3;
    }
}
- (IBAction)backButtonClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (NSMutableArray *)commentArray {
    if (!_commentArray) {
        _commentArray = [NSMutableArray array];
    }
    return _commentArray;
}

- (NSMutableArray *)positionArray {
    if (!_positionArray) {
        _positionArray = [NSMutableArray array];
    }
    return _positionArray;
}

- (NSMutableArray *)jobTypeArray {
    if (!_jobTypeArray) {
        _jobTypeArray = [NSMutableArray array];
    }
    return _jobTypeArray;
}

@end
